import { getRange } from '#utils/index.js';

const getWikiSheet = async (ctx, docId) => {
  const response = await ctx.larkHttp.get('/wiki/v2/spaces/get_node', {
    qs: {
      token: docId,
      obj_type: 'wiki'
    }
  });

  if (response.status == 400 && response.data.code == '131005') {
    return await getDocument(ctx, docId);
  }

  if (response.status !== 200) {
    ctx.fail(response.data.code, response.data.error);
    return null;
  }

  return await getDocument(ctx, response.data.data.node.obj_token);
};

const getDocument = async (ctx, documentId) => {
  const response = await ctx.larkHttp.get(
    `/sheets/v3/spreadsheets/${documentId}/sheets/query`
  );

  if (response.status !== 200) {
    ctx.fail(response.data.code, response.data.error);
    return
  }
  const data = response.data;
  const sheet = data.data.sheets.map((v) => v.sheet_id);
  const promiseList = sheet.map(async (v) => {
    return await getSheet(ctx, documentId, v);
  });

  return await Promise.all(promiseList);
};

const getSheet = async (ctx, documentId, sheetId) => {
  return new Promise(async (resolve, reject) => {
    const response = await ctx.larkHttp.get(
      `/sheets/v3/spreadsheets/${documentId}/sheets/${sheetId}`
    );

    if (response.status !== 200) {
      reject(false);
    }
    const data = response.data.data.sheet.grid_properties;
    const range = getRange(sheetId, data.row_count, data.column_count);
    const sheetReq = await ctx.larkHttp.get(
      `/sheets/v2/spreadsheets/${documentId}/values/${range}`
    );
    if (sheetReq.status !== 200) {
      reject(false);
    }
    const sheetData = sheetReq.data.data.valueRange.values;
    resolve(sheetData);
  });
};

export { getWikiSheet };
